package com.zlt.bkparking.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zlt.bkparking.dto.CarAddressDTO;
import com.zlt.bkparking.dto.ParkingOrderDTO;
import com.zlt.bkparking.entity.*;
import com.zlt.bkparking.mapper.AppUserMapper;
import com.zlt.bkparking.mapper.CarAddressMapper;
import com.zlt.bkparking.mapper.ParkingLotMapper;
import com.zlt.bkparking.mapper.ParkingOrderMapper;
import com.zlt.bkparking.service.PlOrderService;
import com.zlt.bkparking.vo.*;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 停车场管理员，订单管理类
 */
@Service
public class PlOrderServiceImpl implements PlOrderService {

    @Autowired
    private ParkingOrderMapper parkingOrderMapper;

    @Autowired
    private ParkingLotMapper parkingLotMapper;

    @Autowired
    private AppUserMapper appUserMapper;
    
    @Autowired
    private CarAddressMapper carAddressMapper;

    /**
     * 查询停车场订单信息
     * @param parkingOrderDTO
     * @return
     */
    @Override
    public PageInfo<ParkingOrderVO> selectPlOrder(ParkingOrderDTO parkingOrderDTO) {
        if(parkingOrderDTO==null){
            throw new RuntimeException("订单parkingOrderDTO，传参为空");
        }
        ////////////////////等待ActiveUser//////////////////////////////

        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }

        //test


        Integer page = parkingOrderDTO.getPage();
        if (page == null ){
            page = 1;
        }
        Integer limit = parkingOrderDTO.getLimit();
        if (limit == null){
            limit = 5;
        }

        //查询当前停车场管理员，管理了那些停车场
        ParkingLotExample parkingLotExample=new ParkingLotExample();
// 等待        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getUid);
        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());
        List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
        if(parkingLots==null || parkingLots.isEmpty()){
            throw new RuntimeException("当前未绑定停车场");
        }
        List<Integer> plIds=new ArrayList<>();
        for (ParkingLot parkingLot : parkingLots) {
            plIds.add(parkingLot.getPlId());
        }

        ParkingOrderExample parkingOrderExample=new ParkingOrderExample();
        ParkingOrderExample.Criteria criteria = parkingOrderExample.createCriteria();
        criteria.andPlIdIn(plIds);

        //条件查询
        if(parkingOrderDTO.getPoNo()!=null){
            criteria.andPoNoLike("%"+parkingOrderDTO.getPoNo()+"%");
        }
        if(parkingOrderDTO.getAuId()!=null){
            criteria.andAuIdEqualTo(parkingOrderDTO.getAuId());
        }

        if(parkingOrderDTO.getPoStart()!=null){
            criteria.andPoStartGreaterThanOrEqualTo(parkingOrderDTO.getPoStart());
        }

        if(parkingOrderDTO.getPoEnd()!=null){
            criteria.andPoEndLessThanOrEqualTo(parkingOrderDTO.getPoEnd());
        }

        if(parkingOrderDTO.getPoState()!=null){
            criteria.andPoStateEqualTo(parkingOrderDTO.getPoState());
        }

        if(parkingOrderDTO.getAuUsername()!=null){
            AppUserExample appUserExample=new AppUserExample();
            appUserExample.createCriteria().andAuUsernameLike("%"+parkingOrderDTO.getAuUsername()+"%");
            List<AppUser> appUsers = appUserMapper.selectByExample(appUserExample);
            if(appUsers!=null && !appUsers.isEmpty()){
                List<String> auids=new ArrayList<>();
                for (AppUser appUser : appUsers) {
                    auids.add(appUser.getAuId());
                }
                criteria.andAuIdIn(auids);
            }
        }

        parkingOrderExample.setOrderByClause("po_start desc");
        PageHelper.startPage(page,limit);
        List<ParkingOrder> parkingOrders = parkingOrderMapper.selectByExample(parkingOrderExample);
        PageInfo<ParkingOrderVO> pageInfo=new PageInfo(parkingOrders);
        List<ParkingOrderVO> parkingOrderVOList=new ArrayList<>();
        pageInfo.setList(parkingOrderVOList);

        for (ParkingOrder parkingOrder : parkingOrders) {
            ParkingOrderVO parkingOrderVO=new ParkingOrderVO();
            BeanUtils.copyProperties(parkingOrder,parkingOrderVO);
            ParkingLot parkingLot = parkingLotMapper.selectByPrimaryKey(parkingOrder.getPlId());
            if(parkingLot!=null){
                ParkingLotVO parkingLotVO=new ParkingLotVO();
                BeanUtils.copyProperties(parkingLot,parkingLotVO);
                parkingOrderVO.setParkingLotVO(parkingLotVO);
            }

            AppUser appUser = appUserMapper.selectByPrimaryKey(parkingOrder.getAuId());
            if(appUser!=null){
                AppUserVO appUserVO=new AppUserVO();
                BeanUtils.copyProperties(appUser,appUserVO);
                parkingOrderVO.setAppUserVO(appUserVO);
            }

            parkingOrderVOList.add(parkingOrderVO);
        }
        return pageInfo;
    }

    /**
     * 停车场管理员对已经支付的订单做退款处理
     * @param poNo
     * @return
     */
    @Override
    public Boolean orderRefund(String poNo) {
        if(poNo==null){
            throw new RuntimeException("退款订单poNo，传参为空");
        }
        ////////////////////等待ActiveUser//////////////////////////////

        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }

        ParkingOrderExample parkingOrderExample=new ParkingOrderExample();
        parkingOrderExample.createCriteria().andPoNoEqualTo(poNo);
        List<ParkingOrder> parkingOrders = parkingOrderMapper.selectByExample(parkingOrderExample);
        if(parkingOrders==null || parkingOrders.isEmpty()){
            throw new RuntimeException("未查询到该订单");
        }
        ParkingOrder parkingOrder = parkingOrders.get(0);

        //等待处理

        //

        return null;
    }

    /**
     * 根据对应停车场统计对应的订单，按照订单状态进行统计
     * @return
     */
    @Override
    public List<Map<String,Object>> statisticOrder1() {

        ////////////////////等待ActiveUser//////////////////////////////

        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }

        //查询当前停车场管理员，管理了那些停车场
        ParkingLotExample parkingLotExample=new ParkingLotExample();
// 等待        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getUid);
        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());
        List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
        if(parkingLots==null || parkingLots.isEmpty()){
            throw new RuntimeException("当前未绑定停车场");
        }

        List<Integer> plIds=new ArrayList<>();
        for (ParkingLot parkingLot : parkingLots) {
            plIds.add(parkingLot.getPlId());
        }
        System.out.println("plIds=="+plIds);
        List<Map<String, Object>> list = parkingOrderMapper.statistic1(plIds);
        Map<String ,Object> map=new HashMap<>();
        map.put("counts",plIds.size());
        list.add(map);
        System.out.println("list="+list);


        /**
         *
         [
          ['product', 'po_state=1', 'po_state=0',"订单总数"],
          ['pl_id=1', 6, 4 , 10],
          ['pl_id=2', 2, 1 , 3],
         ]
         查询的数据：
         [
         {pl_id=1, count=6, po_state=1},
         {pl_id=1, count=4, po_state=0},
         {pl_id=2, count=1, po_state=0},
         {pl_id=2, count=2, po_state=1},
         {counts=2}
         ]
         */
        List<Object> objectList=new ArrayList<>();
        objectList.add(Arrays.asList(new String[]{"product", "已支付", "待支付", "订单总数"}));
        for (int i = 0; i < list.size(); i++) {
            List<Object> childList=new ArrayList<>();
            objectList.add(childList);
            Map<String, Object> rowMap = list.get(i);
            Integer pl_id = (Integer) rowMap.get("pl_id");
            Integer po_state = (Integer) rowMap.get("po_state");
            Long count = (Long) rowMap.get("count");


        }

        return list;
    }

    @Override
    public List<List<Object>> statisticOrder2(ParkingOrderDTO parkingOrderDTO) {

        /**
         *
         [
         ['product', 'po_state=1', 'po_state=0',"订单总数"],
         ['pl_id=1', 6, 4 , 10],
         ['pl_id=2', 2, 1 , 3],
         ]
         查询的数据：
         [
         {pl_id=1, count=6, po_state=1},
         {pl_id=1, count=4, po_state=0},
         {pl_id=2, count=1, po_state=0},
         {pl_id=2, count=2, po_state=1},
         {counts=2}
         ]
         */

        ////////////////////等待ActiveUser//////////////////////////////

        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }

        //查询当前停车场管理员，管理了那些停车场
        ParkingLotExample parkingLotExample=new ParkingLotExample();
// 等待        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getUid);
        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());
        List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
        if(parkingLots==null || parkingLots.isEmpty()){
            throw new RuntimeException("当前未绑定停车场");
        }

        List<Integer> plIds=new ArrayList<>();
        for (ParkingLot parkingLot : parkingLots) {
            plIds.add(parkingLot.getPlId());
        }

        List<Map<String, Object>> list=new ArrayList<>();
        //查询出当前管理员所有停车场的所有订单
        if(parkingOrderDTO.getPlId()==null){
            System.out.println("plIds=="+plIds);
            list = parkingOrderMapper.statistic1(plIds);
        }else {
            //条件查询
            List<Integer> integerList=new ArrayList<>();
            integerList.add(parkingOrderDTO.getPlId());
            System.out.println(integerList);
            list=parkingOrderMapper.statistic1(integerList);
        }

        //////////////////


        List<List<Object>> listList=new ArrayList<>();
        List<Object> objectList=new ArrayList<>();
        listList.add(objectList);
        String s[]={"parkingName", "未支付", "已支付","订单总数"};
        objectList.addAll(Arrays.asList(s));

        for (ParkingLot parkingLot : parkingLots) {
            Object [] objects=new Object[4];
            List<Object> arrayList = Arrays.asList(objects);
            listList.add(arrayList);
            objects[0]=parkingLot.getPlName();
            //查询该停车场已支付订单、未支付和总订单数量
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> rowMap = list.get(i);
                Integer pl_id = (Integer) rowMap.get("pl_id");
                Integer po_state = (Integer) rowMap.get("po_state");
                Long count = (Long) rowMap.get("count");
                if(pl_id==parkingLot.getPlId()){
                    if(po_state==0){
                        objects[1]=count;
                    }else if (po_state==1){
                        objects[2]=count;
                    }
                }

                Long o=0L;
                Long c=0L;
                if(arrayList.get(1)!=null){
                    o= (Long) arrayList.get(1);
                }
                if(arrayList.get(2)!=null){
                    c= (Long) arrayList.get(2);
                }

                objects[3]=o+c;


            }

        }
        return listList;
    }

    @Override
    public  List<List<Map<String, Object>>> statisticCarAddress(ParkingOrderDTO parkingOrderDTO) {


/*        var datas = [
        ////////////////////////////////////////
  [
        { name: '停车场1总车位', value: 200 },
        { name: '剩余车位', value: 40 },
  ],
        // ////////////////////////////////////////
  [
        { name: '停车场2总车位', value: 500 },
        { name: '剩余车位', value: 100 },
  ],
*/
        ////////////////////等待ActiveUser//////////////////////////////

        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }
        //查询当前停车场管理员，管理了那些停车场
        ParkingLotExample parkingLotExample=new ParkingLotExample();
        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());


        List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
        if(parkingLots==null || parkingLots.isEmpty()){
            throw new RuntimeException("当前未绑定停车场");
        }

        List<List<Map<String, Object>>> listList=new ArrayList<>();

        for (ParkingLot parkingLot : parkingLots) {
            CarAddressExample carAddressExample=new CarAddressExample();
            List<Map<String, Object>> mapList=new ArrayList<>();
            listList.add(mapList);
            CarAddressExample.Criteria criteria = carAddressExample.createCriteria();
            criteria.andPlIdEqualTo(parkingLot.getPlId());
            List<CarAddress> carAddresses = carAddressMapper.selectByExample(carAddressExample);


            if(carAddresses!=null && !carAddresses.isEmpty()){
                CarAddress carAddress = carAddresses.get(0);
                Integer caTotal = carAddress.getCaTotal();
                Integer caSurplus = carAddress.getCaSurplus();
                Map<String, Object> map=new LinkedHashMap<>();
                Map<String, Object> map2=new LinkedHashMap<>();
                map.put("name",parkingLot.getPlName()+" 车位总数");
                map.put("value",caTotal);
                map2.put("name",parkingLot.getPlName()+" 剩余车位数总数");
                map2.put("value",caSurplus);
                mapList.add(map);
                mapList.add(map2);
            }

        }
        System.out.println(listList);
        return listList;
    }

    @Override
    public List<CarAddressVO> selectCarAddress() {
        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }
        //查询当前停车场管理员，管理了那些停车场
        ParkingLotExample parkingLotExample=new ParkingLotExample();
// 等待        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getUid);
        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());
        List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
        if(parkingLots==null || parkingLots.isEmpty()){
            throw new RuntimeException("当前未绑定停车场");
        }

        List<Integer> plIds=new ArrayList<>();
        for (ParkingLot parkingLot : parkingLots) {
            plIds.add(parkingLot.getPlId());
        }
        CarAddressExample carAddressExample=new CarAddressExample();
        carAddressExample.createCriteria().andPlIdIn(plIds);
        List<CarAddress> carAddresses = carAddressMapper.selectByExample(carAddressExample);
        if(carAddresses==null || carAddresses.isEmpty()){
            throw new RuntimeException("当前车位信息为空");
        }
        List<CarAddressVO> carAddressVOS=new ArrayList<>();
        for (CarAddress carAddress : carAddresses) {
            ParkingLot parkingLot = parkingLotMapper.selectByPrimaryKey(carAddress.getPlId());
            ParkingLotVO parkingLotVO=new ParkingLotVO();
            BeanUtils.copyProperties(parkingLot,parkingLotVO);
            CarAddressVO carAddressVO=new CarAddressVO();
            BeanUtils.copyProperties(carAddress,carAddressVO);
            carAddressVO.setParkingLotVO(parkingLotVO);
            carAddressVOS.add(carAddressVO);

        }
        return carAddressVOS;
    }

    @Override
    public Boolean updateCarAddress(CarAddressDTO carAddressDTO) {
        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }
        if(carAddressDTO==null){
            throw new RuntimeException("carAddressDTO数据异常");
        }
        BigDecimal bigDecimal=new BigDecimal(-0.0);
        if(carAddressDTO.getCaTotal()==null || carAddressDTO.getCaSurplus()==null
        || carAddressDTO.getCaTotal()<0 || carAddressDTO.getCaSurplus()<0 || carAddressDTO.getCaSurplus()> carAddressDTO.getCaTotal()
        || carAddressDTO.getCaPrice()==null || (carAddressDTO.getCaPrice().compareTo(bigDecimal)==-1) ){
            throw new RuntimeException("carAddressDTO数据异常");
        }

        CarAddress carAddress=new CarAddress();
        BeanUtils.copyProperties(carAddressDTO,carAddress);
        CarAddressExample carAddressExample=new CarAddressExample();
        carAddressExample.createCriteria().andPlIdEqualTo(carAddressDTO.getPlId());
        int i = carAddressMapper.updateByExampleSelective(carAddress, carAddressExample);
        return i>0;
    }
}
